﻿using WebApp.BLL;
using WebApp.Web.Core.Auth;
using WebApp.BLL.Manage;
using WebApp.Common;
using WebApp.Models;
using WebApp.ViewModels;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApp.Web.Core;

namespace kzjd.rycp.WebApp.Areas.Manage.Controllers
{
    public class MenuController : Controller
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        #region List

        [AuthorizeFilter("Manage.Menu")]
        // GET: Manage/Menu
        public ActionResult List()
        {
            //菜单图标
            ViewBag.NavIcon = new S_menuService().GetMenuIconByAction();

            return View();
        }

        #endregion

        #region MenuListJson

        [AuthorizeFilter("Manage.Menu", ActionType.Ajax)]
        public JsonResult MenuListJson(int page, int rows, string s, string sort, string order)
        {
            S_menuService menuservice = new S_menuService();

            Dictionary<string, object> result = new Dictionary<string, object>();

            int rowscount = 0;

            var list = menuservice.PageList(page, rows, s, sort, order, out rowscount).Select(p => new
            {
                p.Id,
                p.Menukind,
                Menukindstr = CommonStr.GetEnumName(typeof(enmMenuKind), Utils.NvInt(p.Menukind)).ToString(),
                Pmenuid = menuservice.GetMenuname(p.Pmenuid),
                p.Orderseq,
                p.Menuid,
                p.Menuname_zho,
                p.Menuurl,
                p.Menuiconmiddle,
                Status = CommonStr.GetEnumName(typeof(enmMenuStatus), Convert.ToInt32(p.Status)).ToString(),
                Tag_1 = CommonStr.GetEnumName(typeof(enmMenuSystemtype), Utils.NvInt(p.Tag_1)).ToString()
            });

            result.Add("total", rowscount);
            result.Add("rows", list);

            return Json(result);
        }

        [AuthorizeFilter("Manage.Menu", ActionType.Ajax)]
        public JsonResult MenuListTreeJson()
        {
            S_menuService menuservice = new S_menuService();

            menuservice.ClearCache();
            var list = menuservice.ListTree("");

            return Json(list);
        }

        #endregion

        #region 删除
        [AuthorizeFilter("Manage.Menu.Edit", ActionType.Ajax)]
        public JsonResult Delete(string ids)
        {
            try
            {
                new S_menuService().DeleteByIds(ids);

                return Json(new AjaxResult("0", CSMSLang.Get("message_delete_success")));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region 保存
        [AuthorizeFilter("Manage.Menu.Edit", ActionType.Ajax)]
        [ValidateInput(false)]
        public JsonResult Save(string json)
        {
            try
            {
                S_menuService roleservice = new S_menuService();

                //序列化Json数据
                JsonDataModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonDataModel>(json);

                S_menu menu = new S_menu
                {
                    Status = 0
                };

                if (model.Id > 0)
                {
                    menu = roleservice.Find(model.Id);
                }

                //通过反射给属性赋值
                model.SetModelData(menu, true);

                roleservice.Save(menu);

                return Json(new AjaxResult(AjaxResult.RESULT_OK, CSMSLang.Get("message_save_success")));
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return Json(new AjaxResult(AjaxResult.RESULT_ERROR, ex.Message));
            }
        }

        #endregion

        #region 编辑/查看

        [AuthorizeFilter("Manage.Menu.Edit", ActionType.PopupPage)]
        // GET: Manage/Role/Edit/5
        public ActionResult Edit(int id)
        {
            S_menuService menuservice = new S_menuService();

            //所有菜单列表
            List<S_menu> menulist = menuservice.GetAllMenusIncludeHidden();
            //增加一个空项目
            menulist.Insert(0, new S_menu());

            //父菜单的ID
            string pmenuid = Request.QueryString["p"];
            //菜单类型
            string menukind = Request.QueryString["k"];

            var mlist = menulist.Select(p => new
            {
                p.Menuid,
                Menuname_zho = (p.Menukind == enmMenuKind.菜单.ToString("d") ? "　" + p.Menuname_zho : p.Menuname_zho)
            });

            if (id == 0)
            {
                //注意：DropDownList的name属性和ViewBag的key值不能相同，否则会照成SelectedValue失效
                ViewBag.MenuKindList = new SelectList(CommonStr.EnumToList(typeof(enmMenuKind)), "Key", "Value");
                ViewBag.MenuList = new SelectList(mlist, "Menuid", "Menuname_zho");
                ViewBag.MenuStatusList = new SelectList(CommonStr.EnumToList(typeof(enmMenuStatus)), "Key", "Value");
                ViewBag.MenuSystemtypeList = new SelectList(CommonStr.EnumToList(typeof(enmMenuSystemtype)), "Key", "Value");
                return View(new S_menu
                {
                    Pmenuid = pmenuid,
                    Menukind = menukind,
                    Orderseq = menuservice.GetNewSort(pmenuid),
                    Status = (int)enmMenuStatus.Normal,
                    Tag_1 = enmMenuSystemtype.Customer.ToString("d")
                });
            }
            else
            {
                S_menu item = menuservice.Find(id);
                if (item == null)
                {
                    throw new HttpException(404, "Menu(id='" + id.ToString() + "') not found!");
                }
                //注意：DropDownList的name属性和ViewBag的key值不能相同，否则会照成SelectedValue失效
                ViewBag.MenuKindList = new SelectList(CommonStr.EnumToList(typeof(enmMenuKind)), "Key", "Value", item.Menukind);
                ViewBag.MenuList = new SelectList(mlist, "Menuid", "Menuname_zho", item.Pmenuid);
                ViewBag.MenuStatusList = new SelectList(CommonStr.EnumToList(typeof(enmMenuStatus)), "Key", "Value", item.Status);
                ViewBag.MenuSystemtypeList = new SelectList(CommonStr.EnumToList(typeof(enmMenuSystemtype)), "Key", "Value", Utils.NvInt(item.Tag_1));
                return View(item);
            }
        }

        #endregion

        #region 重复验证

        [IgnoreAuthorizeFilter]
        public string ExistCheck(int id, string menuid)
        {
            return new S_menuService().Exist(id, menuid) ? "no" : "yes";
        }

        #endregion

    }
}